#include "Widget.h"
#include <SEUi/SEUi.h>

#include <SEDebug/Log/Log.h>

namespace SEngine
{
    Widget::Widget()
        : m_name("SEngine")
        , m_open(true)
        , m_windowFlags(0)
        , m_isFocused(false)
    {
    }

    Widget &Widget::SetWindowFlag(int flag, bool value)
    { 
        if (value) {
            m_windowFlags |= flag;
        } else {
            m_windowFlags &= ~flag;
        }
        return *this; 
    }


    void Widget::Update(int delta)
    {
        if (m_open) {
            BeginUpdate();
            ImGui::Begin(m_name.c_str(), m_windowFlags & WindowFlags_HideClose ? nullptr : &m_open, m_windowFlags);
            if (!m_open) SignalClose.Invoke();
            m_isFocused = ImGui::IsWindowHovered();
            auto size = ImGui::GetWindowSize();
            auto pos = ImGui::GetWindowPos();
            m_rect = glm::ivec4((int)pos.x, (int)pos.y, (int)size.x, (int)size.y);
            if (ImGui::IsItemVisible()) {
                UpdateImpl(delta);
                EnableEventHandle::OnUpdateImpl(delta);
            }
            ImGui::End();
            EndUpdate();
        }
    }

    void Widget::OnEvent(EventPtr event)
    {
        if (m_isFocused && m_interactor) {
            m_interactor->OnEvent(event);
        }
        EnableEventHandle::OnEventImpl(event);
    }

    bool Widget::IsHoveredWindow() 
    {
        return m_isFocused;
    }


} // namespace SEngine

